//
//  RightImageButton.m
//  MGTV-iPhone
//
//  Created by xiangbo on 2017/7/6.
//  Copyright © 2017年 hunantv. All rights reserved.
//

#import "RightImageButton.h"

@interface  RightImageButton()

@property (nonatomic, assign)CGSize imageSize;//图片大小

@end

@implementation RightImageButton

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //高亮的时候不要自动调整图标
        self.imageView.contentMode = UIViewContentModeLeft;
        self.titleLabel.textAlignment = NSTextAlignmentRight;
        self.imageSize = CGSizeZero;
        self.gapWidth = 0.f;
        self.edgeWidth = 10.f;
        self.wordSpaceWidth = 0.f;
    }
    return self;
    
}

-(CGRect)imageRectForContentRect:(CGRect)contentRect{
    CGFloat imageW = self.imageSize.width;
    CGFloat imageX = contentRect.size.width - self.imageSize.width - self.edgeWidth;
    CGFloat imageH = self.imageSize.height;
    CGFloat imageY = (CGRectGetHeight(self.frame) - imageH) / 2;
    return  CGRectMake(imageX, imageY, imageW, imageH);
}

-(CGRect)titleRectForContentRect:(CGRect)contentRect{
    CGFloat titleW = contentRect.size.width - self.imageSize.width - self.edgeWidth -self.gapWidth - self.edgeWidth;
    CGFloat titleX = self.edgeWidth;
    CGFloat titleH = contentRect.size.height;
    CGFloat titleY = (CGRectGetHeight(self.frame) -titleH) / 2;
    return CGRectMake(titleX, titleY, titleW, titleH);
}

-(void)setTitle:(NSString *)title forState:(UIControlState)state{
    self.frame = [self frameWithTitle:title];
    [super setTitle:title forState:state];
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state{
    self.imageSize = image.size;
    [super setImage:image forState:state];
}

- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state{
    self.frame = [self frameWithTitle:title.string];
    [super setAttributedTitle:title forState:state];
}

- (CGRect)frameWithTitle:(NSString *)title{
    CGFloat titleW = [title sizeWithAttributes:@{NSFontAttributeName: self.titleLabel.font}].width;
    CGRect frame = self.frame;
    frame.size.width = titleW + self.imageSize.width + 2 * self.edgeWidth + self.wordSpaceWidth + self.gapWidth;
    return frame;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
